package com.itheima.health.service.impl;

import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void addOrderSetting(OrderSetting orderSetting) {
        //先判断该日期在数据库是否存在，存在的话更新预约数，不存在则新增该日预约数
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OrderSetting orderDate = orderSettingDao.selectOrderSettingByOrderDate(format.format(orderSetting.getOrderDate()));
        if (orderDate == null) {
            orderSettingDao.insertOrderSetting(orderSetting);
        } else {
            orderSettingDao.updateOrderSetting(orderSetting.getNumber(), format.format(orderSetting.getOrderDate()));
        }
    }

    @Override
    public List<OrderSetting> selectOrderSettingByMonth(Integer year, Integer month) {
        Calendar cal = Calendar.getInstance();
        String startDate = String.format("%d-%d-1", year, month);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        log.info("lastDaylastDaylastDaylastDaylastDaylastDaylastDay:{}", lastDay);
        String endDate = String.format("%d-%d-" + lastDay, year, month);
        return orderSettingDao.selectOrderSettingByMonth(startDate, endDate);

    }

    @Override
    public void updateOrderSetting(Integer number, String date) throws ParseException {

        OrderSetting dbOrderSetting = orderSettingDao.selectOrderSettingByOrderDate(date);
        if (dbOrderSetting != null) {
            orderSettingDao.updateOrderSetting(number, date);
        } else {
            /*  Calendar cal=Calendar.getInstance();
            cal.set(Calendar.YEAR,2024);*/
            //    log.info("stringdatestringdatestringdatestringdate:{}",date);

            OrderSetting orderSetting = new OrderSetting();
            orderSetting.setNumber(number);
            orderSetting.setReservations(0);
            Date date1 = new Date();
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            orderSetting.setOrderDate(date1);
            orderSettingDao.insertOrderSetting(orderSetting);
        }

    }

    @Override
    public OrderSetting findOrderSettingByDate(String date) {
        OrderSetting orderSetting = orderSettingDao.selectOrderSettingByOrderDate(date);
        return orderSetting;
    }
}
